package com.whmnx.chitchat.ui.my;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.icu.text.StringPrepParseException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.orhanobut.logger.Logger;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.base.BaseActivity;
import com.whmnx.chitchat.bean.BaseBean;
import com.whmnx.chitchat.bean.ImgResultBean;
import com.whmnx.chitchat.bean.LoginBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.main.RegisterActivity;
import com.whmnx.chitchat.utils.ImageUtil;
import com.whmnx.chitchat.utils.PhotoUtil;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;

import org.apache.commons.lang3.StringEscapeUtils;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author : huang
 * date   : 2020/7/22 0022 17:24
 * version: 1.0
 *
 * @author Administrator
 */
public class MyInfoActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.iv_user)
    CircleImageView ivUser;
    @BindView(R.id.tv_nickName)
    TextView tvNickName;
    @BindView(R.id.tv_name2)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_com)
    TextView tvCom;
    @BindView(R.id.tv_bumen)
    TextView tvBumen;
    private Dialog dialogHead;
    private Uri imageUri;
    private Uri cropImageUri;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    /* 请求识别码 */
    public static final int CODE_GALLERY_REQUEST = 0xa0;
    public static final int CODE_CAMERA_REQUEST = 0xa1;
    public static final int CODE_RESULT_REQUEST = 0xa2;

    public static int OUTPUT_X = 480;
    public static int OUTPUT_Y = 480;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.my_info_activity);
        setTitle("个人信息");
        ib_back.setOnClickListener(v -> finish());
    }

    @Override
    protected void loadData() {
        ImageUtil.setImage(ivUser, SPUtil.getString(Constants.HEAD_IMG));
        tvNickName.setText(SPUtil.getString(Constants.NICKNAME));
        tvName.setText(SPUtil.getString(Constants.NICKNAME));
        tvPhone.setText(SPUtil.getString(Constants.PHONE));
        tvBumen.setText(SPUtil.getString(Constants.DEP));
        tvCom.setText(SPUtil.getString(Constants.COM));
    }


    @OnClick({R.id.ll_photo, R.id.ll_nick,R.id.ll_1,R.id.ll_2,R.id.ll_3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_photo:
                showHeadDialog();
                break;
            case R.id.ll_1:
                UItils.showToastSafe("请联系管理员");
                break;
            case R.id.ll_2:
                UItils.showToastSafe("请联系管理员");
                break;
            case R.id.ll_3:
                UItils.showToastSafe("请联系管理员");
                break;
            case R.id.ll_nick:
                Intent intentCamera = new Intent();
                intentCamera.setClass(this, ChangeInfoActivity.class);
                startActivityForResult(intentCamera, 100);
                break;
            default:
        }
    }

    private void showHeadDialog() {
        dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_head_portrait2, null);
        view.findViewById(R.id.dialog_shoot).setOnClickListener(this);
        view.findViewById(R.id.dialog_photo_album).setOnClickListener(this);
        view.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        lp.y = 20;
        //将属性设置给窗体
        window.setAttributes(lp);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //拍摄
            case R.id.dialog_shoot:
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(this, "com.whmnx.chitchat.FileProvider", fileUri);
                }
                PhotoUtil.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                //   photoUtils.takePicture(MyUserInfoActivity.this);
                dialogHead.dismiss();
                break;
            //相册
            case R.id.dialog_photo_album:
                PhotoUtil.openPic(this, CODE_GALLERY_REQUEST);
                // photoUtils.takePicture(MyUserInfoActivity.this);
                //  photoUtils.selectPicture(MyUserInfoActivity.this);
                dialogHead.dismiss();
                break;
            //取消
            case R.id.dialog_cancel:
                dialogHead.dismiss();
                break;
            default:
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    tvNickName.setText(data.getStringExtra("name"));
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.FAMILY);
                    EventBus.getDefault().post(messageEvent);
                    break;
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtil.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.whmnx.chitchat.FileProvider", new File(newUri.getPath()));
                    }
                    PhotoUtil.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_RESULT_REQUEST:
                    // Bitmap bitmap = BitmapFactory.decodeFile(cropImageUri.getPath());
                    Bitmap bitmap = PhotoUtil.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        //  flag = true;
                        ivUser.setImageBitmap(bitmap);
                        String url = Constants.UPLOADHEADIMG + "?foldername=HeadImg";
                        List<File> files = new ArrayList<>();
                        files.add(fileCropUri);
                        HttpClient.postImg(this, url, files, new CallBack<List<ImgResultBean>>() {
                            @Override
                            public void onSuccess(List<ImgResultBean> baseBean) {
                                    String url = (String) baseBean.get(0).fullPath;
                                    Map<String, Object> params = new HashMap<>();
                                    params.put("UserID",SPUtil.getString(Constants.USERID));
                                    params.put("HeadImg",url);
                                    HttpClient.get(MyInfoActivity.this, Constants.GETUPDATEHEADIMG, params,new CallBack<BaseBean>() {
                                        @Override
                                        public void onSuccess(BaseBean result) {
                                            if (result.getStatus() == 1){
                                                String url = (String) baseBean.get(0).fullPath;
                                                Logger.i("hhh",result);
                                                SPUtil.put(Constants.HEAD_IMG, url);
                                                MessageEvent messageEvent = new MessageEvent();
                                                messageEvent.setMessageKey(EventConstants.FAMILY);
                                                EventBus.getDefault().post(messageEvent);
                                            }
                                        }
                                    });
                                }
                        });
                    }
                    break;
                default:
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
